package com.koron.css2.clientCenter.impl;

import com.koron.css2.ApplicationConfig;
import com.koron.css2.clientCenter.bean.*;
import com.koron.css2.clientCenter.mapper.*;
import com.koron.css2.meterService.mapper.MsInfoMapper;
import com.koron.css2.serviceManage.bean.UserDiscountBean;
import com.koron.css2.serviceManage.bean.UserInfoBean;
import com.koron.css2.serviceManage.bean.UserMixtureBean;
import com.koron.css2.serviceManage.mapper.UserDiscountMapper;
import com.koron.css2.serviceManage.mapper.UserMixtureMapper;
import com.koron.css2.serviceManage.queryBean.UserMixtureQueryBean;
import com.koron.css2.workflow.ProcessInterface;
import com.koron.util.Constant;
import com.koron.util.Tools;
import com.koron.util.secret.RequestBean;
import com.koron.util.secret.SecretReqUtil;
import org.apache.commons.lang3.StringUtils;
import org.koron.ebs.mybatis.SessionFactory;
import org.swan.bean.MessageBean;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 开户审批处理
 * 
 * @author 甄玉晴
 *
 */
public class OpenUserWorkFlow implements ProcessInterface {

	public MessageBean<?> exec(SessionFactory factory, UserInfoBean userInfo, String billId, String fromNodeCode, int operation) {
		MessageBean<?> info = MessageBean.create(Constant.MESSAGE_INT_SUCCESS, "success", Void.class);
		try {
			// 审批后执行
			if("approval".equalsIgnoreCase(fromNodeCode) && 32 == operation) {
				// 获取新开户的单据信息
				OpenUserMapper mapper = factory.getMapper(OpenUserMapper.class);
				//UserOpenBean bean = mapper.getUserOpenInfoById(billId);
				
				List<UserOpenBean> ulist = mapper.getUserOpenTempInfoById(billId);
				// 获取客户、账户、用户信息
				UserInfoMapper userMapper = factory.getMapper(UserInfoMapper.class);
				AccountInfoMapper accountMapper = factory.getMapper(AccountInfoMapper.class);
				CtmInfoMapper ctmMapper = factory.getMapper(CtmInfoMapper.class);
				
				MsInfoMapper meterMapper = factory.getMapper(MsInfoMapper.class);
				ChangeUserMapper cmapper = factory.getMapper(ChangeUserMapper.class);
				UserPersonDetailMapper upMapper = factory.getMapper(UserPersonDetailMapper.class);
				
				
				List<UserPersonDetailBean> upList = new ArrayList<UserPersonDetailBean>();
				for (UserOpenBean userOpenBean : ulist) {
					AccountInfoBean accountInfo = accountMapper.getAccountInfoById(userOpenBean.getUserAccountTempId(),
							AccountInfoBean.ACCOUNTTEMP);// 获取临时账户信息
					CtmInfoBean ctmInfo = ctmMapper.getCtmInfoById(userOpenBean.getUserCtmTempId(), CtmInfoBean.CTMTEMP);// 获取临时客户信息
					UserBean user = userMapper.getUserInfoById(userOpenBean.getUserInfoTempId(), UserBean.USERTEMP);// 获取临时用户信息
					//检查是否存在该用户编号。不存在的时候才生成新客户，1：正式表user_ctm
					CtmInfoBean checkNo = ctmMapper.getCtmInfoByCtmNo(ctmInfo.getCtmNo(),1);
					if(checkNo == null) {
						ctmInfo.setCreateInfo(userInfo);
						ctmMapper.ctmInfoAdd(ctmInfo, CtmInfoBean.CTM);
					}
					AccountInfoBean returnAccount = accountMapper.getAccountInfoByCode(accountInfo.getAccountNo(), 1);
					//如果账号编号为空，则创建新账户
					if(returnAccount==null) {
						accountInfo.setCreateInfo(userInfo);
						accountMapper.accountInfoAdd(accountInfo, AccountInfoBean.ACCOUNT);
					}
					user.setAccountNo(accountInfo.getAccountNo());
					user.setCtmNo(ctmInfo.getCtmNo());
					//更新临时表数据与正式表一致
					userMapper.userInfoUpdate(user, UserBean.USERTEMP);
					user.setCreateInfo(userInfo);
					userMapper.userInfoAdd(user, UserBean.USER);

					//修改水表状态、用户编号
					if(user.getMeterType().equals("1")) {
						meterMapper.updateMsInfoStatus(user.getMeterNo(), 2);
						meterMapper.updateMsInfoUserNo(user.getMeterNo(), user.getUserNo());
					}
		
					//添加用户编号关联信息 
					userMapper.userRelationHstAdd(Tools.getObjectId(), user.getCtmNo(), user.getUserNo(), user.getAccountNo());
					
					//更新用水人口到UserPersonDetail,循环结束后批量
					List<UserChangePersonBean> userPerson = cmapper.getUserChangePersonById(userOpenBean.getId());
					for (UserChangePersonBean ubean : userPerson) {
						UserPersonDetailBean bean = new UserPersonDetailBean();
						bean.setCreateInfo(userInfo);
						bean.setUserNo(user.getUserNo());
						bean.setCertNo(ubean.getCertNo());
						bean.setCertType(ubean.getCertType());
						bean.setName(ubean.getName());
						bean.setLinkTel(ubean.getLinkTel());
						bean.setComments(ubean.getComments());
						upList.add(bean);
					}
					//更新混合用水
					UserMixtureMapper userMixtureMapper = factory.getMapper(UserMixtureMapper.class);
					UserMixtureQueryBean queryBean = new UserMixtureQueryBean();
					queryBean.setId(userOpenBean.getId());
					queryBean.setUserNo(user.getUserNo());
					List<UserMixtureBean> list = userMixtureMapper.listTemp(queryBean); 
					
					if(list!=null && list.size()>0) {
						List<UserMixtureBean> exists = userMixtureMapper.list(queryBean);
						List<UserMixtureBean> mixtureBeans = new ArrayList<UserMixtureBean>();
						mixtureBeans.addAll(exists);
						for(UserMixtureBean userMixtureBean:list) {
							int isExits = 0;
							for(UserMixtureBean exist:exists) {
								if(exist.getUseWaterType().equals(userMixtureBean.getUseWaterType()) && 
										userMixtureBean.getCostNo().equals(exist.getCostNo())) {
									isExits = 1;
									userMixtureBean.setUpdateInfo(userInfo);
									userMixtureMapper.update(userMixtureBean);
									mixtureBeans.remove(exist);
								}
							}
							if(isExits == 0) {
								userMixtureBean.setCreateInfo(userInfo);
								if(StringUtils.isEmpty(userMixtureBean.getUserNo()))
									userMixtureBean.setUserNo(user.getUserNo());
								userMixtureMapper.insert(userMixtureBean);
							}
							
						}
						for(UserMixtureBean mixtureBean :mixtureBeans) {
							userMixtureMapper.delete(mixtureBean);
						}
						userMixtureMapper.deleteTempById(billId);
					}
					
					//更新费用折扣
					UserDiscountMapper userDiscountMapper = factory.getMapper(UserDiscountMapper.class);
					UserMixtureQueryBean queryBean1 = new UserMixtureQueryBean();
					queryBean1.setId(userOpenBean.getId());
					queryBean1.setUserNo(user.getUserNo());
					List<UserDiscountBean> discountlist = userDiscountMapper.listTemp(queryBean1);
					
					if(discountlist!=null && discountlist.size()>0) {
						List<UserDiscountBean> existslist = userDiscountMapper.list(queryBean);
						List<UserDiscountBean> discountBeans = new ArrayList<UserDiscountBean>();
						discountBeans.addAll(existslist);
						for(UserDiscountBean userDiscountBean:discountlist) {
							int isExits = 0;
							for(UserDiscountBean exist:existslist) {
								if(exist.getCostId().equals(userDiscountBean.getCostId())) {
									isExits = 1;
									userDiscountBean.setUpdateInfo(userInfo);
									userDiscountMapper.update(userDiscountBean);
									discountBeans.remove(exist);
								}
							}
							if(isExits == 0) {
								userDiscountBean.setCreateInfo(userInfo);
								if(StringUtils.isEmpty(userDiscountBean.getUserNo()))
									userDiscountBean.setUserNo(user.getUserNo());
								userDiscountMapper.insert(userDiscountBean);
							}
							
						}
						for(UserDiscountBean discountBean :discountBeans) {
							userDiscountMapper.delete(discountBean);
						}
						userDiscountMapper.deleteTempById(billId);
					}
					user.setTenantId(userInfo.getCurWaterCode());
					//查询此水表是否远传表，是则同步至集抄
					String meterType  =meterMapper.getMeterTypeByMeterNo(user.getMeterNo());
					//将数据同步到集抄系统
					if("2".equals(meterType)&&userInfo.getCurWaterCode().length()==2) {
						//银川系统传至集抄系统
						String resultJc=user.getUserNo()+update(ApplicationConfig.getJcUrl(),user,ctmInfo.getCtmName());
						logger.info("用户信息同步至集抄系统"+resultJc);
					}
				}
				if(upList!=null && upList.size()>0) {
					upMapper.userPersonDetailAddList(upList);
				}
				
			}//开户单废弃操作，将全部水表置为在库
			else if ("approval".equalsIgnoreCase(fromNodeCode) && 16 == operation){
				// 获取新开户的单据信息
				OpenUserMapper mapper = factory.getMapper(OpenUserMapper.class);
				MsInfoMapper msInfoMapper = factory.getMapper(MsInfoMapper.class);
				UserInfoMapper userMapper = factory.getMapper(UserInfoMapper.class);
				List<UserOpenBean> ulist = mapper.getUserOpenTempInfoById(billId);
				for (UserOpenBean userOpenBean:ulist) {
					String meterNo = userMapper.getUserInfoById(userOpenBean.getUserInfoTempId(), UserBean.USERTEMP).getMeterNo();// 获取临时用户信息的水表
					msInfoMapper.updateMsInfoStatus(meterNo,1);
				}
			}
		} catch (Exception e) {
			factory.close(false);
			logger.error("开户审批后续操作失败", e);
			info = MessageBean.create(Constant.MESSAGE_INT_FAIL, "开户审批后续操作失败", Void.class);
		}
		return info;
	}
	 private static String update(String url, UserBean bean,String name){
		 	//获取水表信息
		 	Map<String,Object> data=new HashMap<String,Object>();
		 	//获取表身码
		 	data.put("code", bean.getMeterNo());
		 	data.put("group", bean.getTenantId());
		 	data.put("usn", bean.getUserNo());
		 	data.put("areaId", bean.getClientContractAddr());
		 	data.put("installAddr", bean.getSetupMeterAddr());
		 	data.put("installTime", bean.getSetupMeterDate());
		 	data.put("position", bean.getSetupMeterLocation());
		 	data.put("name", name);
		 	data.put("concentrator", bean.getConcentratorNo());
	    	RequestBean reqBean = new RequestBean();
//	        reqBean.setUrl("http://localhost:8081/syncJc");
	        reqBean.setUrl(url);
	        reqBean.setData(data);
	        String result = null;
	        try {
	            result = SecretReqUtil.sendToJc(reqBean,"updateMeter");
	            
	        }catch (Exception e){
	            logger.error("调用集抄系统失败",e);
	            return e+"";
	        }
	        return result;
	    }
	 @Override
		public MessageBean<?> before(SessionFactory factory, UserInfoBean userInfo, String billId, String fromNodeCode, int operation) {
			return exec(factory, userInfo, billId, fromNodeCode, operation);
		}

		@Override
		public MessageBean<?> after(SessionFactory factory, UserInfoBean userInfo, String billId, String fromNodeCode, String toNodeCode) {
			return null;
		}
}
